/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <boost/pool/singleton_pool.hpp>
#include "Xern/DataStream.hpp"
#include "Xern/DataFilter.hpp"
#include "Packet.hpp"

namespace XernMetaverse
{
    struct PacketPoolTag {};
    typedef boost::singleton_pool<PacketPoolTag, sizeof(Packet)> PacketPool;

    Packet::Packet()
    {
        flags = 0;
        sequenceNumber = 0;
        packetSize = 0;
        sendCount = 0;
    }

    Packet::~Packet()
    {
    }

    void Packet::Decode(const MessageTemplates &templates)
    {
    	DataStream in(buffer.size(), buffer.c_array());

        // Decode the fixed header.
    	in.ReadBig<u8> (flags);
    	in.ReadBig<u32> (sequenceNumber);

        // Ignore the extra header.
        u8 extraLen;
        in.ReadBig<u8> (extraLen);
        in.Skip(extraLen);

        // Enable zero encoding for the body.
        if(flags & FL_ZERO_CODE)
        {
        	boost::shared_ptr<IDataFilter> filter;
        	filter.reset(new ZeroCodeFilter(in.GetFilter()));
        	in.SetFilter(filter);
        }

        // Decode the message payload.

        // Read the mesage id and frequency
        u32 id;
        u8 byte;
        in.ReadBig(byte);

        // Decode the frequency
        MessageTemplate::Frequency freq;

        if(byte == 0xFF)
        {
        	in.ReadBig(byte);
            if(byte == 0xFF)
            {
            	in.ReadBig(byte);
                if(byte == 0xFF)
                {
                    // Fixed frequency.
                	in.ReadBig(byte);
                    id = 0xFFFFFF00 | byte;
                    freq = MessageTemplate::MF_FIXED;
                }
                else
                {
                    // Low frequency.
                	id = byte << 8;
                	in.ReadBig(byte);
                	id = id | byte;
                    freq = MessageTemplate::MF_LOW;
                }
            }
            else
            {
                // Medium frequency.
            	id = byte;
                freq =  MessageTemplate::MF_MEDIUM;
            }
        }
        else
        {
            // High frequency.
        	id = byte;
            freq = MessageTemplate::MF_HIGH;
        }

        // Try to create the message.
        message = CreateMessage(templates, freq, id);
        if(!message)
        {
            fprintf(stderr, "Failed to create message(freq : %d, id : %d). Ignoring a packet payload\n", freq, id);
            return;
        }

        // Read the message.
        message->ReadMessage(in);

        // Decode the appended acks.
        if(flags & FL_ACKS)
        {
            int numacks = buffer[packetSize-1];
            while(numacks > 0)
            {
                u32 ackId;
                in.ReadBig (ackId);
                acks.push_back(ackId);
                numacks--;
            }
        }
    }

    void Packet::Encode()
    {
        assert(message);
        DataStream out(buffer.size(), buffer.c_array());

        // Check if the message is zero encoded.
        if(message->GetTemplate()->encoding == MessageTemplate::ME_ZEROCODED)
            flags |= FL_ZERO_CODE;

        // Encode the flags.
        out.WriteBig<u8> (flags);
        out.WriteBig<u32> (sequenceNumber);
        out.WriteBig<u8> (0); // Extra header len.

        // Enable zero encoding for the message body.
        if(flags & FL_ZERO_CODE)
        {
        	boost::shared_ptr<IDataFilter> filter;
        	filter.reset(new ZeroCodeFilter(out.GetFilter()));
        	out.SetFilter(filter);
        }

        // Write the message header.
        u32 id = message->GetTemplate()->messageId;
        switch(message->GetTemplate()->frequency)
        {
        case MessageTemplate::MF_HIGH:
            out.WriteBig<u8> (id);
            break;
        case MessageTemplate::MF_MEDIUM:
            out.WriteBig<u8> (0xFF);
            out.WriteBig<u8> (id);
            break;
        case MessageTemplate::MF_LOW:
            out.WriteBig<u16> (0xFFFF);
            out.WriteBig<u16> (id);
            break;
        case MessageTemplate::MF_FIXED:
            out.WriteBig<u32> (id);
            break;
        }

        // Write the message data.
        message->WriteMessage(out);

        // Flush the output.
        out.Flush();

        // Write the appended acks.
        if(flags & FL_ACKS)
        {
            int numacks = acks.size();
            for(size_t i = 0; i < numacks; i++)
            {
                out.WriteBig<u32> (acks[i]);
            }

            out.WriteBig<u8> (numacks);
            out.Flush();
        }


        // Store the packet position.
        packetSize = out.GetPosition();

        // Dump the packet.
        /*if(message->GetTemplate()->name == "AgentUpdate")
        {
            FILE *f = fopen("packet.pack", "wb");
            fwrite(buffer.c_array(), packetSize, 1, f);
            fclose(f);
        }*/
    }

    void *Packet::operator new(size_t numbytes)
    {
        assert(numbytes == sizeof(Packet));
        return PacketPool::malloc();
        //return new unsigned char[numbytes];
    }

    void Packet::operator delete(void *pointer)
    {
        PacketPool::free(pointer);
        //delete [] ((unsigned char*)pointer);
    }

}; // namespace Xern
